"""
TCP Server Python绑定
封装TCP Server的C接口函数
"""

import ctypes
from typing import List, Optional


class TCPServerBinding:
    """TCP Server Python绑定类"""
    
    def __init__(self, dll_path: str):
        """
        初始化TCP Server绑定
        
        Args:
            dll_path: DLL文件路径
        """
        self.dll = ctypes.CDLL(dll_path)
        self._setup_function_signatures()
    
    def _setup_function_signatures(self):
        """设置函数签名"""
        # TcpServer_New
        self.dll.TcpServer_New.argtypes = [
            ctypes.c_char_p,
            ctypes.c_int,
            ctypes.c_uint16
        ]
        self.dll.TcpServer_New.restype = ctypes.POINTER(ctypes.c_uint32)
        
        # TcpServer_Delete
        self.dll.TcpServer_Delete.argtypes = [ctypes.POINTER(ctypes.c_uint32)]
        self.dll.TcpServer_Delete.restype = None
        
        # TcpServer_StartAccept
        self.dll.TcpServer_StartAccept.argtypes = [
            ctypes.POINTER(ctypes.c_uint32),
            ctypes.c_int,
            ctypes.c_bool,
            ctypes.c_uint
        ]
        self.dll.TcpServer_StartAccept.restype = None
        
        # TcpServer_IsAcceptComplete
        self.dll.TcpServer_IsAcceptComplete.argtypes = [ctypes.POINTER(ctypes.c_uint32)]
        self.dll.TcpServer_IsAcceptComplete.restype = ctypes.c_bool
        
        # TcpServer_DisconnectClient
        self.dll.TcpServer_DisconnectClient.argtypes = [
            ctypes.POINTER(ctypes.c_uint32),
            ctypes.c_char_p,
            ctypes.c_int
        ]
        self.dll.TcpServer_DisconnectClient.restype = None
        
        # TcpServer_GetClientsIP
        self.dll.TcpServer_GetClientsIP.argtypes = [
            ctypes.POINTER(ctypes.c_uint32),
            ctypes.POINTER(ctypes.c_uint8)
        ]
        self.dll.TcpServer_GetClientsIP.restype = ctypes.POINTER(ctypes.c_char_p)
        
        # TcpServer_GetClient
        self.dll.TcpServer_GetClient.argtypes = [
            ctypes.POINTER(ctypes.c_uint32),
            ctypes.c_char_p,
            ctypes.c_int
        ]
        self.dll.TcpServer_GetClient.restype = ctypes.POINTER(ctypes.c_uint32)
    
    def create_server(self, ip_address: str, port: int) -> Optional[ctypes.POINTER(ctypes.c_uint32)]:
        """
        创建TCP服务器实例
        
        Args:
            ip_address: IP地址字符串
            port: 端口号
            
        Returns:
            TCP服务器句柄，失败返回None
        """
        ip_bytes = ip_address.encode('utf-8')
        handle = self.dll.TcpServer_New(
            ip_bytes,
            len(ip_bytes),
            ctypes.c_uint16(port)
        )
        return handle if handle else None
    
    def delete_server(self, handle: ctypes.POINTER(ctypes.c_uint32)) -> None:
        """
        删除TCP服务器实例
        
        Args:
            handle: TCP服务器句柄
        """
        if handle:
            self.dll.TcpServer_Delete(handle)
    
    def start_accept(self, handle: ctypes.POINTER(ctypes.c_uint32), 
                     duration_ms: int, async_mode: bool = False, 
                     client_count: int = 1) -> None:
        """
        开始接受客户端连接
        
        Args:
            handle: TCP服务器句柄
            duration_ms: 持续时间（毫秒）
            async_mode: 是否异步模式
            client_count: 客户端数量
        """
        if handle:
            self.dll.TcpServer_StartAccept(
                handle,
                ctypes.c_int(duration_ms),
                ctypes.c_bool(async_mode),
                ctypes.c_uint(client_count)
            )
    
    def is_accept_complete(self, handle: ctypes.POINTER(ctypes.c_uint32)) -> bool:
        """
        检查接受连接是否完成
        
        Args:
            handle: TCP服务器句柄
            
        Returns:
            是否完成
        """
        if not handle:
            return False
        
        return self.dll.TcpServer_IsAcceptComplete(handle)
    
    def disconnect_client(self, handle: ctypes.POINTER(ctypes.c_uint32), 
                         client_ip: str) -> None:
        """
        断开指定客户端连接
        
        Args:
            handle: TCP服务器句柄
            client_ip: 客户端IP地址
        """
        if handle:
            ip_bytes = client_ip.encode('utf-8')
            self.dll.TcpServer_DisconnectClient(
                handle,
                ip_bytes,
                len(ip_bytes)
            )
    
    def get_clients_ip(self, handle: ctypes.POINTER(ctypes.c_uint32)) -> List[str]:
        """
        获取客户端IP地址列表
        
        Args:
            handle: TCP服务器句柄
            
        Returns:
            客户端IP地址列表
        """
        if not handle:
            return []
        
        client_count = ctypes.c_uint8()
        clients_ip_ptr = self.dll.TcpServer_GetClientsIP(handle, ctypes.byref(client_count))
        
        if not clients_ip_ptr or client_count.value == 0:
            return []
        
        # 将C字符串数组转换为Python字符串列表
        client_ips = []
        for i in range(client_count.value):
            if clients_ip_ptr[i]:
                ip_str = ctypes.string_at(clients_ip_ptr[i]).decode('utf-8')
                client_ips.append(ip_str)
        
        return client_ips
    
    def get_client(self, handle: ctypes.POINTER(ctypes.c_uint32), 
                   client_ip: str) -> Optional[ctypes.POINTER(ctypes.c_uint32)]:
        """
        获取指定IP的客户端
        
        Args:
            handle: TCP服务器句柄
            client_ip: 客户端IP地址
            
        Returns:
            客户端句柄，失败返回None
        """
        if not handle:
            return None
        
        ip_bytes = client_ip.encode('utf-8')
        client_handle = self.dll.TcpServer_GetClient(
            handle,
            ip_bytes,
            len(ip_bytes)
        )
        
        return client_handle if client_handle else None 